package parse

import (
	"time"

	"github.com/garyburd/redigo/redis"
)

// Redis 库的划分
const (
	DBEnableIP int = iota //存生效的ip
	DBExpireIP
	DBValidateIP //验证过有效
)

// RedisPool redisPool
type RedisPool struct {
	RedisPool *redis.Pool
	ReidsHost string
}

// DBRedisPool 不同的库连接池
type DBRedisPool struct {
	DBPool    map[int]*RedisPool
	RedisHost string
}

//NewDBRedisPool 生成
func NewDBRedisPool(host string) *DBRedisPool {
	pool := &DBRedisPool{
		DBPool:    make(map[int]*RedisPool),
		RedisHost: host,
	}
	return pool
}

// NewRedisPool 生成
func NewRedisPool(host string, db int) *RedisPool {
	redisPool := &RedisPool{ReidsHost: host}
	redisPool.RedisPool = &redis.Pool{
		MaxIdle:     10,
		MaxActive:   1000,
		IdleTimeout: 20 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", host, redis.DialDatabase(db))
			if err != nil {
				return nil, err
			}
			return c, nil
		},
	}
	return redisPool
}

func (d *DBRedisPool) getPool(db int) *RedisPool {
	if v, ok := d.DBPool[db]; ok {
		return v
	}
	pool := NewRedisPool(d.RedisHost, db)
	d.DBPool[db] = pool
	return pool
}

// Do 存储到对应的Redis db
func (d *DBRedisPool) Do(op string, db int, args ...interface{}) (interface{}, error) {
	redisPool := d.getPool(db)
	return redisPool.Do(op, args...)
}

// Del 删除对应库的key
func (d *DBRedisPool) Del(key string, db int) (interface{}, error) {
	redisPool := d.getPool(db)
	return redisPool.Del(key)
}

// Do 存储到Redis,字符串
func (r *RedisPool) Do(op string, args ...interface{}) (interface{}, error) {
	conn := r.RedisPool.Get()
	defer conn.Close()
	//存储到Redis
	return conn.Do(op, args...)
}

// Del 删除Key
func (r *RedisPool) Del(key string) (interface{}, error) {
	return r.Do("del", key)
}
